package com.google.code.jerseyclients.asynchttpclient;

/*
 * Olivier Lamy
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you under the Apache License, Version 2.0 (the
 * "License"); you may not use this file except in compliance
 * with the License.  You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing,
 * software distributed under the License is distributed on an
 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
 * KIND, either express or implied.  See the License for the
 * specific language governing permissions and limitations
 * under the License.
 */

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.net.SocketTimeoutException;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.Future;
import java.util.concurrent.TimeoutException;

import javax.ws.rs.core.MultivaluedMap;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.time.StopWatch;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.google.code.jerseyclients.JerseyHttpClientConfig;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.FluentCaseInsensitiveStringsMap;
import com.ning.http.client.PerRequestConfig;
import com.ning.http.client.ProxyServer;
import com.ning.http.client.Response;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientRequest;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.ClientResponse.Status;
import com.sun.jersey.api.client.CommittingOutputStream;
import com.sun.jersey.api.client.TerminatingClientHandler;
import com.sun.jersey.core.header.InBoundHeaders;

/**
 * created 1 oct. 2010
 * @author <a href="mailto:olamy@apache.org">Olivier Lamy</a> 
 * @version $Id: AsyncHttpClientJerseyClientHandler.java 9 2010-11-04 18:55:54Z oliver.lamy@gmail.com $
 */
public class AsyncHttpClientJerseyClientHandler
    extends TerminatingClientHandler
{
    private Logger log = LoggerFactory.getLogger( getClass() );

    private AsyncHttpClient client;

    private JerseyHttpClientConfig jerseyHttpClientConfig;

    public AsyncHttpClientJerseyClientHandler( AsyncHttpClient client, JerseyHttpClientConfig config )
    {
        this.client = client;
        this.jerseyHttpClientConfig = config;
    }

    /**
     * @see com.sun.jersey.api.client.ClientHandler#handle(com.sun.jersey.api.client.ClientRequest)
     */
    public ClientResponse handle( final ClientRequest clientRequest )
        throws ClientHandlerException
    {

        final BoundRequestBuilder boundRequestBuilder = getBoundRequestBuilder( clientRequest );

        PerRequestConfig perRequestConfig = new PerRequestConfig();
        perRequestConfig.setRequestTimeoutInMs( this.jerseyHttpClientConfig.getReadTimeOut() );

        if ( this.jerseyHttpClientConfig.getProxyInformation() != null )
        {
            ProxyServer proxyServer = new ProxyServer( jerseyHttpClientConfig.getProxyInformation().getProxyHost(),
                                                       jerseyHttpClientConfig.getProxyInformation().getProxyPort() );
            perRequestConfig = new PerRequestConfig( proxyServer, this.jerseyHttpClientConfig.getReadTimeOut() );
        }

        boundRequestBuilder.setPerRequestConfig( perRequestConfig );

        if ( this.jerseyHttpClientConfig.getApplicationCode() != null )
        {
            boundRequestBuilder.addHeader( this.jerseyHttpClientConfig.getApplicationCodeHeader(),
                                           this.jerseyHttpClientConfig.getApplicationCode() );
        }
        if ( this.jerseyHttpClientConfig.getOptionnalHeaders() != null )
        {
            for ( Entry<String, String> entry : this.jerseyHttpClientConfig.getOptionnalHeaders().entrySet() )
            {
                boundRequestBuilder.addHeader( entry.getKey(), entry.getValue() );
            }
        }

        if ( StringUtils.equalsIgnoreCase( "POST", clientRequest.getMethod() ) )
        {

            if ( clientRequest.getEntity() != null )
            {
                final RequestEntityWriter re = getRequestEntityWriter( clientRequest );

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                try
                {
                    re.writeRequestEntity( new CommittingOutputStream( baos )
                    {
                        @Override
                        protected void commit()
                            throws IOException
                        {
                            writeOutBoundHeaders( clientRequest.getHeaders(), boundRequestBuilder );
                        }
                    } );
                }
                catch ( IOException ex )
                {
                    throw new ClientHandlerException( ex );
                }

                boundRequestBuilder.setBody( new ByteArrayInputStream( baos.toByteArray() ) );

            }
        }
        else
        {
            writeOutBoundHeaders( clientRequest.getHeaders(), boundRequestBuilder );
        }
        try
        {
            StopWatch stopWatch = new StopWatch();
            stopWatch.reset();
            stopWatch.start();
            Future<Response> futureResponse = boundRequestBuilder.execute();
            Response response = futureResponse.get();
            int httpReturnCode = response.getStatusCode();
            stopWatch.stop();
            log.info( "time to call rest url " + clientRequest.getURI() + ", " + stopWatch.getTime() + " ms" );
            // in case of empty content returned we returned an empty stream
            // to return a null object
            if ( httpReturnCode == Status.NO_CONTENT.getStatusCode() )
            {
                new ClientResponse( httpReturnCode, getInBoundHeaders( response ),IOUtils
                                        .toInputStream( "" ) , getMessageBodyWorkers() );
            }            
            return new ClientResponse( httpReturnCode, getInBoundHeaders( response ),
                                                                response.getResponseBodyAsStream() == null ? IOUtils
                                                                    .toInputStream( "" ) : response
                                                                    .getResponseBodyAsStream(), getMessageBodyWorkers() );
        }
        catch ( Exception e )
        {
            if ( e.getCause() != null && ( e.getCause() instanceof TimeoutException ) )
            {
                throw new ClientHandlerException( new SocketTimeoutException() );
            }
            throw new ClientHandlerException( e );
        }
    }

    /**
     * @param httpResponse
     * @return
     */
    private InBoundHeaders getInBoundHeaders( Response response )
    {
        InBoundHeaders headers = new InBoundHeaders();
        FluentCaseInsensitiveStringsMap headersMap = response.getHeaders();
        if ( headersMap == null || headersMap.isEmpty() )
        {
            return headers;
        }

        for ( String key : headersMap.keySet() )
        {
            List<String> list = headersMap.get( key );
            headers.put( key, list );
        }
        return headers;
    }

    private void writeOutBoundHeaders( MultivaluedMap<String, Object> metadata, BoundRequestBuilder boundRequestBuilder )
    {
        for ( Map.Entry<String, List<Object>> e : metadata.entrySet() )
        {
            List<Object> vs = e.getValue();
            if ( vs.size() == 1 )
            {
                boundRequestBuilder.addHeader( e.getKey(), headerValueToString( vs.get( 0 ) ) );
            }
            else
            {
                StringBuilder b = new StringBuilder();
                for ( Object v : e.getValue() )
                {
                    if ( b.length() > 0 )
                    {
                        b.append( ',' );
                    }
                    b.append( headerValueToString( v ) );
                }
                boundRequestBuilder.addHeader( e.getKey(), b.toString() );
            }
        }
    }

    private BoundRequestBuilder getBoundRequestBuilder( ClientRequest cr )
    {
        final String strMethod = cr.getMethod();
        final String uri = cr.getURI().toString();
        if ( strMethod.equals( "GET" ) )
        {
            return this.client.prepareGet( uri );
        }
        else if ( strMethod.equals( "POST" ) )
        {
            return this.client.preparePost( uri );
        }
        else if ( strMethod.equals( "PUT" ) )
        {
            return this.client.preparePut( uri );
        }
        else if ( strMethod.equals( "DELETE" ) )
        {
            return this.client.prepareDelete( uri );
        }
        else if ( strMethod.equals( "HEAD" ) )
        {
            return this.client.prepareHead( uri );
        }
        else if ( strMethod.equals( "OPTIONS" ) )
        {
            return this.client.prepareOptions( uri );
        }
        else
        {
            throw new ClientHandlerException( "Method " + strMethod + " is not supported." );
        }
    }

}
